<script lang="ts" setup>
import { ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { House, User, Menu, ShoppingBag } from '@element-plus/icons-vue'
import type {UserVO, ProductRO, TagRO, CartEntity} from "@/api";
import {userService} from '@/service/UserService'
import { productService } from '@/service/ProductService';
import {cartService} from "@/service/CartService";


/////////////////用户信息部分/////////////////////
let userInfo = ref<UserVO>()
userService.getUserInfo().then(res => {
  userInfo.value = res.data
}).catch(err => {
  console.log(err)
  alert("获取用户信息失败！")
})


/////////////////边栏高亮部分/////////////////////
const route = useRoute()
const router = useRouter()

//设置默认的菜单项
const activeMenu = ref(getMenuIndex(route.path))

//监听路由变化
watch(route, (newRoute) => {
  activeMenu.value = getMenuIndex(newRoute.path)
})

//菜单项选择时更新activeMenu
const handleMenuSelect = (index: string) => {
  switch (index) {
    case '1':
      router.push('/main')
      break
    case '2':
      router.push('/order-history')
      break
    case '3-1':
      router.push('/user-profile')
      break
    case '3-2':
      router.push('/cart')
      break
    case '3-3':
      router.push('/favorites')
      break
  }
}

//根据路由路径返回菜单项的index
function getMenuIndex(path: string) {
  switch (path) {
    case '/main':
      return '1'
    case '/order-history':
      return '2'
    case '/user-profile':
      return '3-1'
    case '/cart':
      return '3-2'
    case '/favorites':
      return '3-3'
    default:
      return '1' //默认主页
  }
}

///////////////页面设定部分////////////////
const cartCount = ref(0)

const cart = ref<CartEntity>()
const getCartCount = async () => {
  cartService.getCartInfo(userInfo.value?.id!).then((res) => {
    cart.value = res.data;
    cartCount.value = cart.value.cartProducts!.reduce((total, cartProduct) => {
      return total + cartProduct.quantity!;
    }, 0);
    console.log("Total cart count:", cartCount.value);
  }).catch((err) => {
    console.error("Error fetching cart info:", err);
  });
}

//购物车图标点击事件
const goToCart = () => {
  router.push('/cart')
}

//获取商品列表
const products = ref<ProductRO[]>([]);

// 获取商品信息
productService.getProductInfo().then((res) => {
  if (res && res.data && Array.isArray(res.data)) {
    products.value = res.data;
  }
}).catch((err) => {
  console.log(err);
  alert("获取商品信息失败！");
});

const goToProductDetail = (id: string) => {
  // 使用query传参
  router.push({
    path: '/product-detail',
    query: {
      queryId: id
    }
  })
}
</script>

<template>
  <div class="h-full flex">
    <!--边栏-->
    <aside class="fixed top-0 left-0 w-40 bg-primary-100 text-primary-800 border-r-2 border-primary-300 h-full">
      <div class="overflow-y-auto">
        <el-menu :default-active="activeMenu" @select="handleMenuSelect">
          <el-menu-item index="1">
            <template #title>
              <el-icon><House /></el-icon>主页
            </template>
          </el-menu-item>
          <el-menu-item index="2">
            <template #title>
              <el-icon><Menu /></el-icon>历史订单
            </template>
          </el-menu-item>
          <el-sub-menu index="3">
            <template #title>
              <el-icon><User /></el-icon>个人中心
            </template>
            <el-menu-item-group title="用户">
              <el-menu-item index="3-1">个人中心</el-menu-item>
            </el-menu-item-group>
            <el-menu-item-group title="商品">
              <el-menu-item index="3-2">购物车</el-menu-item>
              <el-menu-item index="3-3">收藏夹</el-menu-item>
            </el-menu-item-group>
          </el-sub-menu>
        </el-menu>
      </div>
    </aside>

    <!--主容器-->
    <div class="flex-1 flex flex-col ml-20%"> <!-- Add left margin for sidebar -->
      <!--顶栏-->
      <header class="fixed top-0 left-0 w-full text-right text-sm bg-primary-200 p-4 border-b-2 border-primary-300 z-100">
        <div class="flex items-center justify-end space-x-4 mt-3">
          <el-avatar :size="36"></el-avatar>
          <span data-testid="user-info" class="ml-2">Hi, {{ userInfo?.name }}</span>
        </div>
      </header>

      <!--------------------------------变化区域-------------------------------->
      <main class="flex-1 p-4 overflow-auto">
        <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
          <div data-testid="product-card" class="product-card bg-white p-4 rounded-lg shadow-lg cursor-pointer" v-for="product in products" :key="product.title">
            <div  @click="goToProductDetail(product.id!)">
              <div class="product-image mb-4 h-xs">
                <img :src="product.image" alt="product title" class="w-full h-auto object-cover rounded-md"/>
              </div>
              <div class="product-info">
                <h3 class="text-xl font-semibold mb-2">{{ product.title }}</h3>
                <p class="text-gray-600 text-sm mb-2">{{ product.description }}</p>
                <span class="text-lg font-bold">￥{{ (product.price ? product.price.toFixed(2) : '0.00')}}</span>
              </div>
              <div class="product-tags mt-2 flex flex-wrap gap-2">
               <span v-for="tag in product.tags" :key="tag.name" class="tag inline-block bg-gray-200 text-gray-700 text-sm px-3 py-1 rounded-full">
                  {{ tag.name }}
               </span>
              </div>
            </div>
          </div>
        </div>
      </main>


      <!-- 购物车悬浮图标 -->
      <div @click="goToCart" class="fixed bottom-5 right-5 bg-white rounded-full cursor-pointer text-center z-100 shadow-lg w-16 h-16 flex items-center justify-center">
        <el-icon><ShoppingBag /></el-icon>
        <span v-if="cartCount > 0" class="absolute top-[0rem] right-[0rem] bg-#fb7299 text-white text-xs w-5 h-5 rounded-full flex items-center justify-center">
          {{ cartCount }}
        </span>
      </div>
      <!--------------------------------变化区域-------------------------------->


    </div>
  </div>
</template>

<style scoped>
aside {
  position: fixed;
  top: 0;
  left: 0;
  width: 20%;
  height: 100%;
  border-right: 0.2em solid #E5E7EB;
  z-index: 100;
}

header {
  left: 20%;
  width: 80%;
  background-color: #F1F5F9;
  height: 10%;
}

main{
  margin-top: 10%;
}
</style>
